package com.lixun.passwordbook.slice;

import com.lixun.passwordbook.MainAbility;
import com.lixun.passwordbook.ResourceTable;
import com.lixun.passwordbook.pojo.Colors;
import com.lixun.passwordbook.pojo.Constant;
import com.lixun.passwordbook.util.FileData;
import com.lixun.passwordbook.util.AESUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.utils.TextAlignment;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.IDialog;
import ohos.agp.window.dialog.ToastDialog;
import ohos.agp.window.service.WindowManager;
import ohos.app.Context;
import ohos.data.dataability.DataAbilityPredicates;
import ohos.data.rdb.ValuesBucket;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.net.Uri;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_CONTENT;

public class WelcomeAbilitySlice extends AbilitySlice {
    static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201, "WelcomeStart");
    private final String FACE_KEY="xswlawsl!lspyyds";
    private static final String BASE_URI = "dataability:///com.lixun.passwordbook.DataAbility";
    private static final String DATA_PATH = "/pwb";
    private static final String DB_COLUMN_PASSWOED = "password";
    private static final String DB_COLUMN_ID = "id";
    private DataAbilityHelper databaseHelper;
    /**
     * DIALOG_BOX_CORNER_RADIUS
     */
    public static final float DIALOG_BOX_CORNER_RADIUS = 36.0f;

    private Context mContext;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_welcome);
        mContext = this;
        databaseHelper = DataAbilityHelper.creator(this);
        //创建设置按钮
        createSetBtn();
        //设置颜色模式
        colorMode();
        //设置状态栏颜色
        setStatusBarColor();
    }

    /**
     * 设置状态栏颜色
     */
    private void setStatusBarColor() {
        getWindow().addFlags(WindowManager.LayoutConfig.MARK_TRANSLUCENT_NAVIGATION);
        getWindow().setStatusBarColor(Color.TRANSPARENT.getValue());
    }

    /**
     * 切换颜色模式
     */
    private void colorMode(){
        DirectionalLayout abilityWelcome = (DirectionalLayout) findComponentById(ResourceTable.Id_ability_welcome);
        Text text = (Text) findComponentById(ResourceTable.Id_ability_welcome_text);
        TextField text1 = (TextField) findComponentById(ResourceTable.Id_welcome_set_password);
        TextField text2 = (TextField) findComponentById(ResourceTable.Id_welcome_confirm_password);
        boolean dark_mode = Colors.getDarkMode();
        ShapeElement shapeElement = new ShapeElement();
        ShapeElement element;
        Color color;
        if (dark_mode){
            HiLog.info(LABEL, "设置为深色模式");
            shapeElement.setRgbColor(Colors.backgroundColorDark);
            element = new ShapeElement(mContext,ResourceTable.Graphic_detailed_text_field_dark);
            color = Colors.textColorDark;
        } else {
            HiLog.info(LABEL, "设置为常规模式");
            shapeElement.setRgbColor(Colors.backgroundColor);
            element = new ShapeElement(mContext,ResourceTable.Graphic_detailed_text_field);
            color = Colors.textColor;
        }
        abilityWelcome.setBackground(shapeElement);
        text.setTextColor(color);
        text1.setTextColor(color);
        text2.setTextColor(color);
        text1.setBackground(element);
        text2.setBackground(element);
    }

    /**
     * 创建设置按钮
     */
    private void createSetBtn(){
        Component component = findComponentById(ResourceTable.Id_welcome_set);
        Text password1 = (Text)findComponentById(ResourceTable.Id_welcome_set_password);
        Text password2 = (Text)findComponentById(ResourceTable.Id_welcome_confirm_password);
        Button updateBtn;
        if (component instanceof Button) {
            updateBtn = (Button) component;
            updateBtn.setClickedListener(view -> {
                String pwd1 = password1.getText();
                String pwd2 = password2.getText();
                setPWD(pwd1,pwd2);
            });
        }
    }


    /**
     * 设置锁定密码
     */
    private void setPWD(String pwd1,String pwd2){
        String results;
        if (pwd1 == null || pwd1.isEmpty()){
            results = "请输入密码";
        } else if(pwd1.equals(pwd2)){
            setPWD(stringToMD5(pwd1));
            setData(pwd1);
            Constant.setKEY(pwd1);
            HiLog.info(LABEL,"key"+Constant.getKEY());
            faceDialog();
            results = "设置成功";
        } else {
            results = "确认密码与密码不相同，请重新输入。";
        }
        new ToastDialog(this)
                .setText(results)
                // Toast显示在界面底部
                .setAlignment(LayoutAlignment.BOTTOM)
                .show();
    }

    /**
     * stringToMD5
     * @param plainText 需要加密的数据
     * @return 加密后的数据
     */
    public static String stringToMD5(String plainText) {
        byte[] secretBytes = null;
        String newText = plainText + Constant.SALT;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(
                    newText.getBytes());
            HiLog.info(LABEL,"md5 yes");
        } catch (NoSuchAlgorithmException e) {
            HiLog.info(LABEL,"没有这个md5算法");
            throw new RuntimeException("没有这个md5算法！");
        }
        String md5code = new BigInteger(1, secretBytes).toString(16);
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        HiLog.info(LABEL,"2md5长度"+md5code.length());
        HiLog.info(LABEL,"2md5"+md5code);
        return md5code;
    }

    /**
     * 设置文本数据
     * @param pwd 密码
     */
    private void setPWD(String pwd){
        Context context = getApplicationContext();
        FileData fileData = new FileData();
        fileData.setBoolean(context,"first",false);
        fileData.setString(context,"lxpwd",pwd);
    }

    /**
     * 跳转到主界面
     */
    private void toMain() {
        //设置isFrist为false
        MainAbilitySlice.setIsFirst(false);
        Intent secondIntent = new Intent();
        // 指定待启动FA的bundleName和abilityName
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(getBundleName())
                .withAbilityName(MainAbility.class.getName())
                .build();
        secondIntent.setOperation(operation);
        // 通过AbilitySlice的startAbility接口实现启动另一个页面
        startAbility(secondIntent);
        // 进入暂停状态通过onForeground可再次启动
        terminate();
    }

    /**
     * 设置面部识别成功后提取的密码
     * @param key face密钥
     * @return 是否成功
     */
    private Boolean setData(String key) {
        DataAbilityPredicates predicates = new DataAbilityPredicates();
        predicates.equalTo(DB_COLUMN_ID, 1);
        ValuesBucket valuesBucket = new ValuesBucket();
        valuesBucket.putString(DB_COLUMN_PASSWOED, AESUtils.encrypt(FACE_KEY,key));
        try {
            if (databaseHelper.update(Uri.parse(BASE_URI + DATA_PATH), valuesBucket, predicates) != -1) {
                HiLog.info(LABEL, "update 成功");
                return true;
            }
        } catch (DataAbilityRemoteException | IllegalStateException exception) {
            HiLog.error(LABEL, "update: dataRemote exception | illegalStateException");
        }
        return false;
    }

    /**
     * 提示是否开启面部识别功能
     */
    private void faceDialog() {
        Context context = getApplicationContext();
        FileData fileData = new FileData();
        CommonDialog commonDialog = new CommonDialog(this);
        commonDialog.setTitleText("              是否启用面部识别功能");
        commonDialog.setContentText("启用后，启动APP点击解锁按钮开始面部识别。");
        commonDialog.setCornerRadius(DIALOG_BOX_CORNER_RADIUS);
        commonDialog.setAlignment(TextAlignment.CENTER);
        commonDialog.setSize(MATCH_CONTENT, MATCH_CONTENT);
        commonDialog.setAutoClosable(true);
        commonDialog.setButton(IDialog.BUTTON1, "No", (iDialog, var) -> {
            fileData.setBoolean(context,"face_switch",false);
            iDialog.destroy();
            toMain();
        });
        commonDialog.setButton(IDialog.BUTTON2, "Yes", (iDialog, var) -> {
            fileData.setBoolean(context,"face_switch",true);
            iDialog.destroy();
            toMain();
        });
        commonDialog.show();
    }
    /**
     * 提示隐私政策
     */
    private void privacyDialog() {

        CommonDialog dialog = new CommonDialog(getContext());
        dialog.setTitleText("隐私政策");
        dialog.setButton(IDialog.BUTTON2, "好的，了解了！", (iDialog, i) -> iDialog.destroy());
        dialog.setButton(IDialog.BUTTON1, "我不想看！", (iDialog, i) -> terminate());
        Component container = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_ability_welcome_privacy_dialog, null, false);
        dialog.setContentCustomComponent(container);
        dialog.setSize(MATCH_CONTENT, MATCH_CONTENT);
        dialog.show();
    }

    @Override
    public void onActive() {
        super.onActive();
        privacyDialog();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
